<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Libraries\Error;
use App\Models\AttendanceGroup;
use App\Models\ClockIn;
use App\Models\Company;
use App\Models\Employee;
use App\Models\WorkAttendance;
use App\Models\WorkAttendanceMonth;
use App\Models\WorkAttendanceMonthRecord;
use App\Models\WorkAttendanceRecord;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;

class MiniClockInController extends ApiController
{



    public function show(Request $request) {

        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $employee_id = $userInfo['employee_id'];
        $user = Employee::where('employee_id',$employee_id)->where('status',1)->first();
        if (empty($user)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
//        $uid = '29221';
        $company_id = $userInfo['company_id'];

        $clock_in = ClockIn::where('company_id',$company_id)->where('status',1)->orderBy('ci_id',"desc")->first();
        $where = [];
        $where['company_id'] = $company_id;
        $where['status'] = 1;

        $attendance_group = AttendanceGroup::getList($where);
        $company = Company::where('company_id',$company_id)->first();


        $where = [];
        $where['date'] = date("Y-m-d");
        $where['company_id'] = $company_id;
        $where['employee_id'] = $employee_id;
        $where['status'] = 1;
        $workAttendance = WorkAttendance::getList($where);

        $workAttendanceRecord = WorkAttendanceRecord::getList($where);

        return showError(Error::ERR_OK,[
            'clockIn'=>$clock_in,//wifi
            'employee'=>$user,//员工
            'company'=>$company,//公司
            'workAttendance'=>$workAttendance,//今日打卡
            'workAttendanceRecord'=>$workAttendanceRecord,//今日打卡明细
            'attendanceGroup'=>$attendance_group,//考勤规则
        ]);
    }

    public function daydetail(Request $request) {
        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $employee_id = $userInfo['employee_id'];
        $user = Employee::where('employee_id',$employee_id)->where('status',1)->first();
        if (empty($user)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
//        $uid = '29221';
        $company_id = $userInfo['company_id'];
        $where = [];
        $where['date'] = $request->date;
        $where['company_id'] = $company_id;
        $where['employee_id'] = $employee_id;
        $where['status'] = 1;
        $workAttendance = WorkAttendance::getList($where);

        return showError(Error::ERR_OK,[
            'workAttendance'=>$workAttendance,
            'employee'=>$user,
        ]);
    }

    public function monthdetail(Request $request) {
        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $employee_id = $userInfo['employee_id'];
        $user = Employee::where('employee_id',$employee_id)->where('status',1)->first();
        if (empty($user)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
//        $uid = '29221';
        $company_id = $userInfo['company_id'];
        $where = [];
        $where['month'] = $request->month;
        $where['company_id'] = $company_id;
        $where['employee_id'] = $employee_id;
        $where['status'] = 1;
        $work_attendance_month = WorkAttendanceMonth::getList($where);

        return showError(Error::ERR_OK,[
            'workAttendanceMonth'=>$work_attendance_month,
            'employee'=>$user,
        ]);
    }

    public function workattendancecreate(Request $request) {
        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $employee_id = $userInfo['employee_id'];
        $employee = Employee::where('employee_id',$employee_id)->where('status',1)->first();
        if (empty($employee)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
//        $uid = '29221';
        $company_id = $userInfo['company_id'];

        //打卡
        $date = date('Y-m-d H:i:s');
        $dayymd = date('Y-m-d');
        $month = date('Y-m');
        $time = date('H:i:s');
        $week = date('w');
        $day = date('j');

        $where = [];
        $where['status'] = 1;

        $attendance_group = AttendanceGroup::where('company_id',$company_id)->where('status',1)->first();
        switch ($week)
        {
            case 0:
                $key = 'ag_sun';
                break;
            case 1:
                $key = 'ag_mon';
                break;
            case 2:
                $key = 'ag_tue';
                break;
            case 3:
                $key = 'ag_wed';
                break;
            case 4:
                $key = 'ag_thu';
                break;
            case 5:
                $key = 'ag_fri';
                break;
            case 6:
                $key = 'ag_sat';
                break;

        }
        $clock_time = $attendance_group[$key];
        $work_attendance_month = WorkAttendanceMonthRecord::where('employee_id',$employee_id)->where('company_id',$company_id)->where("month",$month)->first();
        if (!empty($work_attendance_month)) {
            $dayNmorning_1 = "day".($day-1)."_morning_status";
            $dayNmorningtime_1 = "day".($day-1)."_morning";
            $dayNnight_1 = "day".($day-1)."_night_status";
            $dayNnighttime_1 = "day".($day-1)."_night";
            if (empty($work_attendance_month->$dayNmorning_1)
                && empty($work_attendance_month->$dayNmorningtime_1)
                && empty($work_attendance_month->$dayNnight_1)
                && empty($work_attendance_month->$dayNnighttime_1)
            ) {
                $work_attendance_month->$dayNmorning_1 = 3;
                $work_attendance_month->$dayNnight_1 = 3;
                //要不要造每天的打卡记录 待定
            }

        }

        if (empty($clock_time) || $clock_time == "休息" ) {
            if (empty($work_attendance_month)) {
                $work_attendance_month = new WorkAttendanceMonthRecord();
                $work_attendance_month->employee_id = $employee_id;
                $work_attendance_month->company_id = $company_id;
                $work_attendance_month->month = $month;
                $work_attendance_month->ctime = time();
            } else {
                $work_attendance_month->mtime = time();
            }
            $dayNmorning = "day".$day."_morning_status";
            $dayNnight = "day".$day."_night_status";
            $work_attendance_month->$dayNmorning = 6;
            $work_attendance_month->$dayNnight = 6;
            $work_attendance_month->save();

            return showError(Error::ERR_OK,[],"休息,不打卡");
        }
        $clock_time = str_replace("早晚 ","",$clock_time);
        $clock_time = str_replace(";","",$clock_time);
        $clock_time = explode("~",$clock_time);
        $start_time = $clock_time[0];
        $end_time = $clock_time[1];

        $work_attendance =WorkAttendance::where('employee_id',$employee_id)->where('clock_in','like','%'.date('Y-m-d').'%')->first();
        if ($work_attendance != null && $work_attendance->id>0) {
            $work_attendance->clock_in = $date;
            $work_attendance->daily_attendance = (strtotime($work_attendance['first_stage_duty'])-strtotime($work_attendance['first_stage_work']))/3600;
            $work_attendance->first_stage_duty = $date;
            //比较算状态
            $status = 1;
            if ($time <= $end_time) {
                //早退
                $status = 5;
            }
            $work_attendance->status = $status;
            //更新月度明细表
            $dayNnight = "day".$day."_night_status";
            $dayNnighttime = "day".$day."_night";

            $work_attendance_month->$dayNnight = $status;
            $work_attendance_month->$dayNnighttime = $date;
            $work_attendance_month->mtime = time();

            $work_attendance->mtime = time();
        } else {
            $work_attendance = new WorkAttendance();
            $work_attendance->employee_id = $employee_id;
            $work_attendance->company_id = $company_id;
            $work_attendance->name = $employee['name'];
            $work_attendance->organization_id = $employee['organization_id'];
            $work_attendance->clock_in = $date;
            $work_attendance->first_stage_work = $date;
            $status = 1;
            if ($time > $start_time) {
                //早退
                $status = 2;
            }
            $work_attendance->status = $status;

            if (empty($work_attendance_month)) {
                $work_attendance_month = new WorkAttendanceMonthRecord();
                $work_attendance_month->employee_id = $employee_id;
                $work_attendance_month->company_id = $company_id;
                $work_attendance_month->month = $month;
                $work_attendance_month->ctime = time();
            } else {
                $work_attendance_month->mtime = time();
            }
            $dayNmorning = "day".$day."_morning_status";
            $dayNmorningtime = "day".$day."_morning";
            $work_attendance_month->$dayNmorning = $status;
            $work_attendance_month->$dayNmorningtime = $date;
            $work_attendance_month->save();

            $work_attendance->ctime = time();
        }


        $work_attendance->save();

        $work_attendance_record = new WorkAttendanceRecord();
        $work_attendance_record->ctime = time();

        $work_attendance_record->employee_id = $employee_id;
        $work_attendance_record->company_id = $company_id;
        $work_attendance_record->clock_in_date = $dayymd;
        $work_attendance_record->clock_in_hours = $time;
        $work_attendance_record->source = "小程序";
        $work_attendance_record->devices = "手机";
        $work_attendance_record->clock_in_place = !empty($request->place)?$request->place:"公司";
        $work_attendance_record->status = $status;

        $work_attendance_record->save();

        return showError(Error::ERR_OK);

    }

}
